package com.saret.dictionary;

import com.google.inject.Singleton;
import com.saret.utils.FileLocator;
import com.saret.utils.StringUtils;
import com.saret.utils.UtfFileHandle;
import com.sun.org.apache.xml.internal.utils.DefaultErrorHandler;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.*;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.math.BigDecimal;
import java.nio.channels.NonWritableChannelException;
import java.util.Collection;

/**
 * @author biniam.gebremichael
 * @since 12/28/11
 */

@Singleton
public class SaveResult {


    Document document;
    Element root;
    Element current;

    public SaveResult() {
        this.document = DocumentHelper.createDocument();
        root = document.addElement("dictionary");
    }

    public void addWord(String word, Collection<String> meaning) {
        current = root.addElement("word");
        current.addAttribute("name", word);
        for (String s : meaning) {
            current.addElement("meaning").addText(s);
        }
    }

    public void addExample(String ln1, String address1, String ln2, String address2, double score) {
        String regs = ".*\\.*(\\w*[\\.|/]\\w+\\.\\w+)/.*";
        String shortAddress1 = StringUtils.match(address1, regs, 1);
        String shortAddress2 = StringUtils.match(address2, regs, 1);
        Element example = current.addElement("example");
        example.addAttribute("score", String.format("%.2f", score));
        example.addElement("english").addAttribute("url", address1).addAttribute("urlName", shortAddress1).addText(ln1);
        example.addElement("dutch").addAttribute("url", address2).addAttribute("urlName", shortAddress2).addText(ln2);
        System.out.print(".");
    }

    public void save(File file) {
        try {
            if (current == null || current.element("example") == null) {
                System.out.println("No translation examples found for \"" + file.getName().replace(".xml", "") + "\" in the lookup domain");
            } else {
                save(document, file);
                saveHtml(document, new File(file.getParent(), file.getName().replace(".xml", ".html")));
                UtfFileHandle.write(new File(file.getParent(), file.getName().replace(".xml", ".sql")), saveSql(document));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public  void save(Document document, File file) throws Exception {
        XMLWriter writer = new XMLWriter(new FileWriter(file), OutputFormat.createPrettyPrint());
        writer.write(document);
        writer.close();
        System.err.println("\n result saved in " + file.getAbsolutePath());
    }


    public String saveSql(Document xml) throws Exception {
        StringBuilder builder = new StringBuilder();
        for (Object o : xml.getRootElement().element("word").elements()) {
            Element example = (Element) o;
            if (example.getQName().getName().equals("example")) {
                Double score = Double.valueOf(example.attributeValue("score"));
                if(score<0.55){
                    continue;
                }
                Element dutch, english = null;
                for (Object o2 : example.elements()) {
                    if (((Element) o2).getQName().getName().equals("english")) {
                        english = example.element("english");
                    } else if (((Element) o2).getQName().getName().equals("dutch")) {
                        dutch = example.element("dutch");


                        builder.append("INSERT INTO translation (text_en,source_en,link_en,text_nl,source_nl,link_nl,score) values (")
                                .append("\'")
                                .append(english.getText().replace("\n",""))
                                .append("\',\'")
                                .append(english.attributeValue("url"))
                                .append("\',\'")
                                .append(link(english.attributeValue("url")))
                                .append("\',\'")
                                .append(dutch.getText().replace("\n",""))
                                .append("\',\'")
                                .append(dutch.attributeValue("url"))
                                .append("\',\'")
                                .append(link(dutch.attributeValue("url")))
                                .append("\',")
                                .append(example.attributeValue("score"))
                                .append(");\n");
                    }
                }
            }
        }
        return builder.toString();
    }

    private  String link(String url){
        String regX =                 "\\w{3,5}://([.a-zA-Z0-9_\\-]+)/.*$";
        return  StringUtils.match(url, regX, 1);
    }

    public  void saveHtml(Document xml, File htmlFile) throws Exception {
        File xsl = FileLocator.getConfigFile("translate", "result.xslt");
        //File html = new File(FileLocator.getWorkingDir(), "student.html");

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(new StreamSource(xsl));
        transformer.setErrorListener(new DefaultErrorHandler(true));
        DocumentResult result = new DocumentResult();
        transformer.transform(new DocumentSource(xml), result);
        Document transformedDoc = result.getDocument();
        save(transformedDoc, htmlFile);
    }

    public  void main(String[] args) throws Exception {
        for (File xml : FileLocator.getWorkingDir().listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".xml");
            }
        })) {
            Document xmlDocument = new SAXReader().read(xml);
            saveHtml(xmlDocument, new File(xml.getParent(), xml.getName().replace(".xml", ".html")));
            System.out.println("saveSql(xml) = " + saveSql(xmlDocument));
        }
    }


}
